<?php

namespace Sharks\Core\Support\Storage;

use Sharks\Core\AppContext;


/**
 * Storage 的文件工具类
 * 将数组转移为文件存储或将文件存储转为数组
 * @package Sharks\Core\Support\Storage
 */
class StorageArrayUtils {

    /**
     * 将数组文件写为php文件,存储在Storage文件夹
     * @param $storageDest
     * @param array $data
     * @internal param string $storageModule
     */
    public static function write($storageDest, array $data) {
    	$storagePath = AppContext::instance()->path()->app->storage;
        if (!is_dir($storagePath)) {
            mkdir($storagePath, 0700, true);
        }
        $content = array();
        $content[] = "<?php";
        $content[] = "";
        $content[] = "// Generator By Sharks StorageArrayUtils";
        $content[] = "return " . var_export($data, true);
        $content[] = ";";
        file_put_contents($storagePath . '/' . $storageDest, implode(PHP_EOL, $content));
    }

    /**
     * 读取在Storage文件夹的php文件,
     * @param $storageDest
     * @return mixed
     * @throws
     */
    public static function read($storageDest, array $default = array()) {
        $storagePath = AppContext::instance()->path()->app->storage;
        
        if (file_exists($storagePath . '/' .$storageDest)) {
        	$array = require($storagePath . '/' .$storageDest);
        	if (is_array($array)) {
        		return $array;
            }
        
        }
        
        if (is_null($default)) {
        	throw new InvalidArgumentException(sprintf('无法载入路径为 %s 的文件', $storageDest));
        }
        else {
        	return $default;
        }
    }
}